package com.lbd99.data.lbd.service;
import com.alibaba.fastjson.JSON;
import com.lbd99.data.lbd.dao.*;
import com.lbd99.data.lbd.vo.*;
import com.lbd99.data.utils.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 收益
 */
@Service
public class ProfitService {
    @Autowired
    TUserMapper tUserMapper;
    @Autowired
    TWalletMapper tWalletMapper;
    @Autowired
    private TIncomeMapper tIncomeMapper;
    @Autowired
    private TTransferLogMapper tTransferLogMapper;
    @Autowired
	SysAccountMapper sysAccountMapper;
    @Autowired
    TTransferLogService tTransferLogService;


    

    public void transfer(int otherUserId, double ifipNum) {
        //被转矿晶的用户对象
        TUser otherUser=tUserMapper.selectByPrimaryKey(otherUserId);
        if (otherUser.getpId()==-1){ //说明被转矿晶已经是顶级用户
            return;
        }
        int level=10;
        parentIncomeTransfer(otherUserId,ifipNum,level,otherUser);

        //===============================================================
//        if(otherUser.getIsUse()==0){
//            otherUser.setIsUse(1);
//        	tUserMapper.updateByPrimaryKey(otherUser);
//        }
        //===============================================================


    }
    private  void parentIncomeTransfer( int otherUserId, double ifipNum,int resultNumLevel,TUser otherUser){
        String parentIds=	getParentIds(otherUserId,"",resultNumLevel);
        if (parentIds==null || "".equals(parentIds)){
            return;
        }
        String[]  parentId=  parentIds.split(",");
        if (parentId!=null && parentId.length>0) {
            for (int i=0;i<parentId.length;i++) {
                if (i==0){  //直接推荐人(上一级)
                    String parentIdStr= parentId[i];
                    TWallet wallet2=tWalletMapper.selectByUserId(Integer.parseInt(parentIdStr));
                    Map  map2=formatIFIVGetMap(wallet2.getIfiv().doubleValue());
                    Double ifip1= (Double) map2.get("ifip");
                    Double ifiv1= (Double) map2.get("ifiv");

                    double ifipNum2=ifipNum*0.2;
                    if (ifipNum>wallet2.getIfiv().doubleValue()/5.8){
                        ifipNum2=(wallet2.getIfiv().doubleValue()/5.8)*0.2;
                    }
                    if (ifipNum2==0){
                        continue;
                    }

                    TWallet wallet3=new TWallet();
                    wallet3.setUserId(Integer.parseInt(parentIdStr));
                    boolean boolTrans=tTransferLogService.compareCurrtimeAndTransfirsttime(otherUserId);
                    if (boolTrans){
                        wallet3.setIfip(new BigDecimal(wallet2.getIfip().doubleValue()+StrUtil.keep4decimal(ifipNum2*ifip1)) ); //5%矿晶
                        wallet3.setIfiv(new BigDecimal( wallet2.getIfiv().doubleValue()+ StrUtil.keep4decimal(ifipNum2*ifiv1)));  //20%矿场
                    }else{
                        wallet3.setIfiv(new BigDecimal( wallet2.getIfiv().doubleValue()+ StrUtil.keep4decimal(ifipNum2*ifip1)));  //5%矿场
                    }

                    tWalletMapper.updateByUserId(wallet3);

                    //#######添加到收益表#########【start】#####################################################
                    TIncome record=new TIncome();
                    record.setUserId(-1);
                    record.setCreateBy("后台充值");
                    record.setpId(Integer.parseInt(parentIdStr));
                    record.setUpdateTime(new Date());
                    record.setCreateTime(new Date());
                    record.setIfipNum(ifipNum);
                    record.setOtherUserId(otherUserId);

                    Map map=new HashMap<>();
                    map.put("ifipNum2",ifipNum2);
                    if (boolTrans){
                        map.put("ifipRate",ifip1);
                        record.setParentIncomeIfip(StrUtil.keep4decimal(ifipNum2*ifip1));

                        map.put("ifivRate",ifiv1);
                        record.setParentIncomeIfiv(StrUtil.keep4decimal(ifipNum2*ifiv1));
                    }else{
                        map.put("ifivRate",ifip1);
                        record.setParentIncomeIfiv(StrUtil.keep4decimal(ifipNum2*ifip1));
                        record.setParentIncomeIfip(0.0);
                    }
                    record.setUpdateBy(JSON.toJSONString(map));
                    tIncomeMapper.insertSelective(record);
                    //#######添加到收益表#########【end】#####################################################

                    //---------------添加到转账记录表中【转入】------------------start-----------------------------
                    TTransferLog tTransferLog2 = new TTransferLog();
                    tTransferLog2.setCreateTime(new Date());
                    tTransferLog2.setUpdateBy("【后台充值收益】被充值用户otherUserId:"+otherUserId+",兑换矿晶为:"+ifipNum);
                    tTransferLog2.setUpdateTime(new Date());
                    if (boolTrans){
                        tTransferLog2.setIfip(StrUtil.keep4decimal(ifipNum2*ifip1));
                        tTransferLog2.setIfiv(StrUtil.keep4decimal(ifipNum2*ifiv1));
                        tTransferLog2.setCreateBy("0");
                    }else{
                        tTransferLog2.setIfip(0.0);
                        tTransferLog2.setIfiv(StrUtil.keep4decimal(ifipNum2*ifip1));
                        tTransferLog2.setCreateBy("1");
                    }

                    //0-转入，1-转出
                    tTransferLog2.setType(0);//转入
                    tTransferLog2.setUserId(Integer.parseInt(parentIdStr));
                    tTransferLog2.setUid(wallet2.getUid());
                    tTransferLogMapper.insert(tTransferLog2);
                    //---------------添加到转账记录表中【转入】------------------end-----------------------------

                } else{  //不是直接推荐人(上一级 以上)
                    String parentIdStr=parentId[i];
                    TWallet wallet2=tWalletMapper.selectByUserId(Integer.parseInt(parentIdStr));
                    boolean bool= isIntercept(Integer.parseInt(parentIdStr));
                    if (bool==false){
                        continue;
                    }
                    TWallet wallet3=new TWallet();
                    wallet3.setUserId(Integer.parseInt(parentIdStr));

                    double ifipNum2=ifipNum*0.2;
                    if (ifipNum>wallet2.getIfiv().doubleValue()/5.8){
                        ifipNum2=(wallet2.getIfiv().doubleValue()/5.8)*0.2;
                    }
                    if (ifipNum2==0){
                        continue;
                    }

                    double rate=getIFIP(i+1);
                    wallet3.setIfiv(new BigDecimal(wallet2.getIfiv().doubleValue()+ StrUtil.keep4decimal(ifipNum2*rate)));
                    tWalletMapper.updateByUserId(wallet3);
                    //#######添加到收益表#########【start】#####################################################
                    TIncome record=new TIncome();
                    record.setUserId(-1);
                    record.setCreateBy("后台充值");
                    record.setpId(Integer.parseInt(parentIdStr));
                    record.setUpdateTime(new Date());
                    record.setCreateTime(new Date());
                    record.setIfipNum(ifipNum);
                    record.setOtherUserId(otherUserId);
                    record.setParentIncomeIfiv(StrUtil.keep4decimal(ifipNum2*rate));
                    record.setParentIncomeIfip(0.0);
                    Map map=new HashMap<>();
                    map.put("ifipNum2",ifipNum2);
                    map.put("ifivRate",rate);
                    record.setUpdateBy(JSON.toJSONString(map));
                    tIncomeMapper.insertSelective(record);
                    //#######添加到收益表#########【end】#####################################################

                    //---------------添加到转账记录表中【转入】------------------start-----------------------------
                    TTransferLog tTransferLog2 = new TTransferLog();
                    tTransferLog2.setCreateTime(new Date());
                    tTransferLog2.setCreateBy("1");
                    tTransferLog2.setUpdateBy("【后台充值收益】被充值用户otherUserId:"+otherUserId+",兑换矿晶为:"+ifipNum);
                    tTransferLog2.setUpdateTime(new Date());
                    tTransferLog2.setIfip(0.0);
                    tTransferLog2.setIfiv(StrUtil.keep4decimal(ifipNum2*rate));
                    //0-转入，1-转出
                    tTransferLog2.setType(0);//转入
                    tTransferLog2.setUserId(Integer.parseInt(parentIdStr));
                    tTransferLog2.setUid(wallet2.getUid());
                    tTransferLogMapper.insert(tTransferLog2);
                    //---------------添加到转账记录表中【转入】------------------end-----------------------------
                }
            }
        }
    }



    /**
     * 				小节点			中节点			大节点		超大节点
     矿场数			10万以下	10万-----50万	50万----200万	200万以上
     *首次推荐奖励	 25%			27%				28%				30%
     * @param p  矿场
     * @return
     */
    private  Map formatIFIVGetMap(double p){
        Map map=new HashMap<>();
        if(p<10*10000){
            map.put("ifip",0.05);
            map.put("ifiv",0.2);
        }else if(p>=10*10000 && p<50*10000){
            map.put("ifip",0.07);
            map.put("ifiv",0.2);
        }else if(p>=50*10000 && p<200*10000){
            map.put("ifip",0.08);
            map.put("ifiv",0.2);
        }else if(p>=200*10000){
            map.put("ifip",0.1);
            map.put("ifiv",0.2);
        }
        return  map;
    }

    private  boolean  isIntercept(Integer parentId){
        boolean result=false;
        TWallet wallet2=tWalletMapper.selectByUserId(parentId);
        int sonNum=tUserMapper.selectCountByPid(parentId);
        double p=wallet2.getIfiv().doubleValue();
        if(p<10*10000){  //小节点
            if (sonNum>=2){  //大于等于2个才满足收益
                result=true;
            }
        }else if(p>=10*10000 && p<50*10000){ //中节点
            if (sonNum>=4){ //大于等于4个才满足收益
                result=true;
            }
        }else if(p>=50*10000 && p<200*10000){  //大节点
            if (sonNum>=6){ //大于等于6个才满足收益
                result=true;
            }
        }else if(p>=200*10000){   //超大节点
            if (sonNum>=8){  //大于等于8个才满足收益
                result=true;
            }
        }
        return  result;
    }

    /**
     1-2层       5%
     3-5层       2%
     6-10层      1%
     */
    public  double  getIFIP(int level){
        double result=0.0;
        if (level>=1 && level<=2){
            result=0.05;
        }else if(level>=3 && level<=5){
            result=0.02;
        }else if(level>=6 && level<=10){
            result=0.01;
        }
        return  result;
    }

    /**
     *  获得上级所有的节点
     * @param id
     * @param sumResult
     * @param level
     * @return
     */
    private  String getParentIds(int id,String sumResult,int level){
        Integer pid= tUserMapper.selectByPrimaryKey(id).getpId();
        if (pid.intValue()==-1 || level==0 ){
            return  sumResult;
        }else{
            String[] sumResultArr=sumResult.split(",");
            if ((sumResultArr.length >=level) && (!"".equals(sumResult))){
                return  sumResult;
            }
            sumResult=sumResult+pid+",";
            return getParentIds(pid,sumResult,level);
        }
    }


}
